<?php
$scf_data = [];
function main_handler($event, $context) {
    global $scf_data;
    $scf_data['IS_SCF'] = true;
    // 处理php文件
    print "start main PHP\n";
    system("mkdir -p /tmp/cache");
    system("mkdir -p /tmp/framework/sessions");
    system("mkdir -p /tmp/framework/cache");
    system("mkdir -p /tmp/framework/views");
    system("chmod -R 755 /tmp");
    system("/var/lang/php7/bin/php -v");
    require __DIR__.'/bootstrap/autoload.php';
    $app = require __DIR__.'/bootstrap/app.php';

    //处理定时任务
    if(isset($event->Type) && $event->Type == "Timer"){ // 定时触发器
        if (is_file(__DIR__ . "/wsConfig.json")) {
            $wsConfig = json_decode(file_get_contents(__DIR__ . '/wsConfig.json'), 1);
            foreach ($wsConfig as $k => $v) {
                $scf_data[$k] = $v;
            }
            unset($wsConfig);
        }
        $event->httpMethod = 'POST';
        if($event->TriggerName == "tencentDataAnalysis"){
            $path = "/admin/tencentDataAnalysis";
            echo "=======".$path."==============";
        }else {
            $path = '/admin/test'; // 路由
        }
        $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
        $request = \Illuminate\Http\Request::create($path,$event->httpMethod,[], [], [], []);
        $response = $kernel->handle($request);
        $content = $response->getContent();
        \Illuminate\Support\Facades\DB::disconnect();
        $headers = [
            'Content-Type'  => 'application/json;charset=utf-8',
            'Access-Control-Allow-Origin'  => '*',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers' => 'x-requested-with,content-type',
        ];
        return array(
            'isBase64Encoded' => false,
            'statusCode' => 200,
            'headers' => $headers,
            'body' => $content
        );
    }else{
        //过滤OPTIONS请求方式
        if ($event->httpMethod == 'OPTIONS') {
            $headers = getHeaders();
            $content = ['code' => '99', 'msg' => 'error', 'data' => ''];
            return array(
                'isBase64Encoded' => false,
                'statusCode' => 200,
                'headers' => $headers,
                'body' => json_encode($content)
            );
        }
        $headers = get_object_vars($event->headers);
        if($event->requestContext->path == "/"){
            $event->path = substr($event->path, strlen($event->requestContext->path));
            $scf_data['host'] = $headers["x-api-scheme"]."://".$headers["host"]; //加上域名
        }else{
            $event->path = substr($event->path, strlen($event->requestContext->path . "/"));
            $scf_data['host'] = $headers["x-api-scheme"]."://".$headers["host"] . "/" . $event->requestContext->stage . $event->requestContext->path; // 加上域名
        }
        if ($event->path == "") {
            $event->path = 'index.html';
        }
        if ($headers["host"] == "dl.wegouer.com"){
            $event->path = 'agent/' . $event->path;
        }
        if ($event->path == "agent/") {
            $event->path = 'agent/index.html';
        }
        if ($event->path == "manage/") {
            $event->path = 'manage/index.html';
        }
        if ($event->path == "saas/" || $event->path == "saas") {
            $event->path = 'saas/index.html';
        }
        // 处理js, css文件
        if (preg_match('#\.html.*|\.js.*|\.css.*|\.html.*#', $event->path)) {
            return resources($event->path, false);
        }
        // 处理图片
        if (preg_match('#\.gif.*|\.jpg.*|\.png.*|\.jepg.*|\.swf.*|\.bmp.*|\.ico.*#', $event->path)) {
            return resources($event->path, true);
        }
        if (is_file(__DIR__ . "/wsConfig.json")) {
            $wsConfig = json_decode(file_get_contents(__DIR__ . '/wsConfig.json'), 1);
            foreach ($wsConfig as $k => $v) {
                $scf_data[$k] = $v;
            }
            unset($wsConfig);
        }
        //腾讯云地图API key 微信号：微微开发 注册腾讯地图 获得
        $scf_data['apiKey'] = 'DD6BZ-RTV6U-5C6VH-BTXIA-BLNMK-Y7BPK';
        //获取ip地址
        if (isset($event->requestContext->sourceIp)){
            $_SERVER["REMOTE_ADDR"] = $scf_data['ip'] = $event->requestContext->sourceIp;
        }else{
            $scf_data['ip'] = '';
        }
        list($requestParams, $content, $cookie, $file) = handleParams($event, $headers);
        $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
        $request = \Illuminate\Http\Request::create($scf_data['host']."/".$event->path, $event->httpMethod, $requestParams, $cookie, $file, [], $content);
        $response = $kernel->handle($request);
        $content = $response->getContent();
        //释放数据库连接
        \Illuminate\Support\Facades\DB::disconnect();
        //获取返回结果
        $result = json_decode($content, true);
        if(empty($result) && !empty($content)){
            if(strpos($content, "<xml>") !== false){
                return array(
                    'isBase64Encoded' => false,
                    'statusCode' => 200,
                    'headers' => array('Content-Type' => 'text/xml;charset=utf-8', "Access-Control-Allow-Origin" => "*", 'Cache-Control' => "max-age=86400"),
                    'body' => $content
                );
            }else {
                return array(
                    'isBase64Encoded' => false,
                    'statusCode' => 200,
                    'headers' => array('Content-Type' => 'text/html;charset=utf-8', "Access-Control-Allow-Origin" => "*", 'Cache-Control' => "max-age=86400"),
                    'body' => $content
                );
            }
        }
        //规定code=3为下载信息
        if (isset($result['code']) && $result['code'] == 3) {
            $filename = $result['data'];
            $handle = fopen($filename, 'r');
            $re = fread($handle, filesize($filename));
            return array(
                'isBase64Encoded' => true,
                'statusCode' => 200,
                'headers' => array(
                    "Content-type" => "application/octet-stream",
                    "Content-Disposition" => "attachment; filename=" . $result['name'],
                    'Accept-Ranges' => 'bytes',
                ),
                'body' => base64_encode($re),
            );
        }
        $headers = getHeaders();
        return array(
            'isBase64Encoded' => false,
            'statusCode' => 200,
            'headers' => $headers,
            'body' => $content
        );
    }
}

function handleParams($event, $headers){
    $requestParam = $cookie = $file = [];
    $content = '';
    if(!empty($event->queryString)) {
        foreach ($event->queryString as $k => $v) {
            $requestParam[$k] = $v;
        }
    }
    if($event->httpMethod == "POST"){
        if (strpos($headers["content-type"], "application/json") !== false) { // json数据
            $requestParam = array_replace($requestParam, json_decode($event->body, true));
        }elseif (strpos($headers["content-type"], "multipart/form-data") !== false) {
            $formDataTag = "multipart/form-data; boundary=";
            $key = "--" . str_replace($formDataTag, "", $headers["content-type"]);
            $params = preg_split("/[\\s]*${key}-*[\\s]*/", $event->body);
            array_pop($params);
            array_shift($params);
            $temp = [];
            foreach ($params as $str) {
                $strArr = explode("\r\n\r\n", $str);
                if (count($strArr) < 2) {
                    $strArr = explode("\n\n", $str);
                }
                $string = preg_replace("/[\\s\\S]*Content-Disposition: form-data; name=\"([^\"]+)\"[\\s\\S]*/", "$1", $strArr);
                if ($string[0] === 'file') { // 文件类型
                    $temp[$string[0]] = isset($string[1]) ? $string[1] : "";
                } else {
                    $temp[$string[0]] = isset($string[1]) ? $string[1] : "";
                }
            }
            $requestParam = array_replace($requestParam, $temp);
            unset($temp);
        }elseif (!empty($event->body)) {
            if (is_string($event->body)) {
                $content = $event->body;
            } else if (is_array($event->body)) {
                $requestParam = array_replace($requestParam, $event->body);
            }
            $GLOBALS['HTTP_RAW_POST_DATA'] = $event->body;
        }
    }
    if(!empty($headers["cookie"])){
        foreach ((array)explode(";", $headers["cookie"]) as $item){
            $item = explode("=", $item);
            $cookie[$item[0]] = isset($item[1]) ? $item[1] : "";
        }
    }
    if(!empty($file)){
        foreach ($file as &$item){
            $files = json_decode($item, true);
            $temp_file = tempnam(sys_get_temp_dir(), "php"); // 生成临时文件
            file_put_contents($temp_file, base64_decode($files["content"])); // 把文件流写入临时文件
            $item = ["name" => $files["name"], "type" => $files["type"], "tmp_name" => $temp_file, "error" => 0, "size" => $files["size"]];
        }
        unset($item);
    }
    return [$requestParam, $content, $cookie, $file];
}

function resources($path, $base64 = false){
    $filename = "/var/user/public/" . $path;
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    $headers = [
        'Content-Type' => '',
        'Cache-Control' => "max-age=8640000",
        'Accept-Ranges' => 'bytes',
    ];
    return array(
        'isBase64Encoded' => $base64,
        'statusCode' => 200,
        'headers' => $headers,
        'body' =>$base64 ? base64_encode($contents) : $contents
    );
}

function getHeaders(){
    $headers = [
        'Content-Type' => 'application/json;charset=utf-8',
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Allow-Headers' => 'x-requested-with,content-type',
    ];
    return $headers;
}

?>
